<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:27
 */


namespace app\api\controller;

use app\common\controller\Common;
use app\common\controller\Core;
use my\RedisPackage as redis;
use think\Request;
use think\Response;
use think\exception\HttpResponseException;
use think\Db;

/**
 * 前台公共控制器
 * @package app\index\controller
 */
class Auth extends Common
{
    /**
     *
     * @var Request Request 实例
     */
    protected $request;
    public $core = '';
    protected $userInfo = [];
    protected $store_id;
    protected $storeInfo = [];//门店详情

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';

    protected $redis = null;
    protected $cachekey = null; //缓存变量名
    protected $basket = []; //私有数组，存放商品信息

    protected $store = 50;

    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->core = new Core();

        // 控制器初始化
        $this->_initialize();
    }

    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header("Access-Control-Allow-Origin: " . $this->request->server('HTTP_ORIGIN'));
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');
        }
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
            }
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
            }
        }
        $token =  $this->request->post('token');
        // 系统开关
        if (!config('web_site_status')) {
            $this->result('站点已经关闭，请稍后访问~');
        }
        // 检测是否需要验证登录
        if (!$this->match($this->noNeedLogin)) {
            //检测是否登录
            if (!$token) {
                $this->result('', null, 203);
            } else {
                $u = Db::name('qt_users')
                    ->field('id,avatar,phone,status,create_time,group,work_status,post_id,store_id,role,is_add,work_number,real_name')
                    ->where(['group'=>'2'])
                    ->where('app_token', $token)
                    ->find();
                if (empty($u)) {
                    $this->result('账号在别处登录，请重新登录', '', 203);
                }
                if ($u['status'] == '2') {
                    $this->result('正在审核中。。。', '', 203);
                }
                if ($u['status'] == '1') {
                    $this->result('账号有问题，请联系管理员', '', 203);
                }
                $this->userInfo = $u;
                $this->store_id = $u['store_id'];
                $storeInfo = Db::name('qt_store')->where('id', $u['store_id'])->find();
                $this->storeInfo = $storeInfo;
                //获取用户访问授权
//                $model = $this->request->module();
//                $controller = $this->request->controller();
//                $action = $this->request->action();
//                $userMenu =$model.'/'.$controller.'/'.$action;
//                $userRole = Db::name('qt_user_role')->alias('r')
//                    ->field('rm.*')
//                    ->leftJoin('qt_user_role_menu rm','r.id = rm.role_id')
//                    ->leftJoin('qt_user_menu m','rm.menu_id = m.id')
//                    ->where(['m.url_value'=>$userMenu,'r.id'=>$u['role']])
//                    ->find();
//                if(empty($userRole)){
//                    $this->result('没有权限操作', '', 203);
//                }
            }
        }
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码，默认为0
     * @param string $type 输出类型，支持json/xml/jsonp
     * @param array $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 200, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'time' => $this->request->server('REQUEST_TIME'),
            'data' => $data,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = 200;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }


    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     * @return boolean
     */
    protected function match($arr = [])
    {
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr) {
            return false;
        }
        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($this->request->action()), $arr) || in_array('*', $arr)) {
            return true;
        }

        // 没找到匹配
        return false;
    }

    protected function check_repeat($key, $time = 60)
    {
        $redis = new redis();
        if (!$redis->exists($key)) {
            $redis->set($key, time(), $time);
            return true;
        } else {
            return false;
        }
    }

    //任务完成，清楚redis的key
    protected function del_rekey($key)
    {
        $redis = new redis();
        if ($redis->exists($key)) {
            $redis->del($key);
            return true;
        } else {
            return false;
        }
    }

    //获取当前方法的key
    protected function get_keys($token)
    {
        $action = request()->controller();
        $aclist = request()->action();
        $name = $action . '-' . $aclist;
        $key = $name . '_' . $token;
        return $key;
    }

    //图片公用接口上传
    public function doupload()
    {
        $file = request()->file("imgurl");
        if (empty($file)) {
            $this->result('请上传图片', '', 204);
        }
        if ($file) {
            //最大3m
            $info = $file->validate(['size' => 5145728, 'ext' => 'jpg,png,jpeg,gif,bmp'])->move('../public/uploads');
            if ($info) {
                $imgurl = 'uploads/' . $info->getSaveName();
                $image = \think\Image::open("../public/" . $imgurl);
                // 按照原图的比例生成一个最大为600*600的缩略图替换原图
                $image->thumb(600, 600)->save("../public/" . $imgurl);
                $data1 = array(
                    'path' => $imgurl,
                    'name' => $info->getSaveName(),
                    'module' => 'index',
                    'md5' => md5($info->getSaveName()),
                    'thumb' => $imgurl,
                    'url' => '1',
                    'siza' => '0',
                    'mime' => $info->getExtension(),
                    'ext' => '0',
                    'sha1' => sha1($info->getSaveName()),
                    'create_time' => time(),
                    'update_time' => time(),
                );
                //var_dump($data);die;
                $re = Db::name('admin_attachment')->insertGetId($data1);
                $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
                $img = $http_type . $_SERVER['SERVER_NAME'] . '/' . $imgurl;
                if ($re) {
                    $info = [
                        'imgurl' => $img,
                        'img_id' => $re,
                    ];
                    $this->result('上传成功', $info, 200);
                } else {
                    $this->result('上传失败，请稍后重试', '', 204);
                }
            } else {
                //上传失败获取错误信息
                $this->result($file->getError(), '', 204);
            }
        } else {
            $this->result('请上传图片', '', 204);
        }
    }

    /**
     * base64图片上传
     */
    public function doupload_base64()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data['imgurl'])) {
                $this->result('请上传图片', '', 204);
            }
            $bg = $data['imgurl'];//获取图片流
//            $str =base64_encode(base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $bg)));
//            if($str!=$bg){
//                $this->result('请上传正确的图片','',204);
//            }
            $image_content = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $bg));
            $filename = time() . rand('1111', '9999') . '.jpg';
            $path = 'uploads/images/' . date('Ymd');
            $dir = $path . '/' . $filename;
            if (!is_dir($path)) {
                mkdir($path);
            }
            file_put_contents($dir, $image_content);
            $imgurl = 'uploads/images/' . date('Ymd') . '/' . $filename;
            $data1 = array(
                'path' => $imgurl,
                'name' => $filename,
                'module' => 'index',
                'md5' => md5($filename),
                'thumb' => $imgurl,
                'url' => '1',
                'siza' => '0',
                'mime' => $filename,
                'ext' => '0',
                'sha1' => sha1($filename),
                'create_time' => time(),
                'update_time' => time(),
            );
            //var_dump($data);die;
            $re = Db::name('admin_attachment')->insertGetId($data1);
            $attac = get_img_path($re);
            $data = array(
                'imgurl' => $attac,
                'img_id' => $re,
            );
            $this->result('上传成功', $data, 200);
        } else {
            $this->result('error', '', 204);
        }
    }

}

